<script>
import { computed, provide } from '@vue/runtime-core'
export default {
  name: 'XtxTabs',
  props: {
    modelValue: {
      type: [String, Number],
      default: '',
    },
  },
  setup(props, { emit }) {
    // props 中的属性发送改变给 activeName
    const activeName = computed(() => props.modelValue)
    // 将选中卡片的 name 给后代组件
    provide('activeName', activeName)

    // 点击选项卡
    const tabClick = (name, index) => {
      // 更新父组件的 activeName
      emit('update:modelValue', name)
      // 触发一个点击自定义事件
      emit('tab-click', { name, index })
    }
    return { tabClick, activeName }
  },
  render() {
    // 获取插槽内容
    const panels = this.$slots.default()
    console.log('panels', panels)
    // 动态的 panel 集合
    const dynamicPanels = []
    panels.forEach((item) => {
      // 静态
      if (item.type.name === 'XtxTabsPanel') {
        dynamicPanels.push(item)
      } else {
        // v-for 渲染的
        item.children.forEach((item) => {
          dynamicPanels.push(item)
        })
      }
    })

    const nav = (
      <nav>
        {dynamicPanels.map((item, i) => (
          <a
            onClick={() => this.tabClick(item.props.name, i)}
            class={{ active: item.props.name === this.activeName }}
          >
            {item.props.label}
          </a>
        ))}
      </nav>
    )
    return <div class="xtx-tabs">{[nav, dynamicPanels]}</div>
  },
}
</script>
<style lang="less">
.xtx-tabs {
  background: #fff;
  > nav {
    height: 60px;
    line-height: 60px;
    display: flex;
    border-bottom: 1px solid #f5f5f5;
    > a {
      width: 110px;
      border-right: 1px solid #f5f5f5;
      text-align: center;
      font-size: 16px;
      &.active {
        border-top: 2px solid @xtxColor;
        height: 60px;
        background: #fff;
        line-height: 56px;
      }
    }
  }
}
</style>
